const Router = require('@koa/router');//导入koa-router模块
const { User } = require('../databases'); // 导入 User 模型
const userSchema = require('../schemas/userSchema'); // 导入 userSchema 模型
const validate = require('../middewares/validate'); // 导入 validate 中间件
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt');
const jwtCheck = require('../middewares/jwtcheck');

const userRouter = new Router({ //实例化用户相关的子路由对象
  prefix: '/user' // 设置路由前缀
});

//http://localhost:3000/user/
userRouter.get('/', jwtCheck, async (ctx, next) => {
  const users = await User.findAll()
  ctx.body = {
    status: 200,
    message: 'User home page',
    data: users
  };
  return;
});
//http://localhost:3000/user/add
userRouter.post('/add', validate(userSchema), async (ctx, next) => {
  const { username, password } = ctx.validatedBody;
  const hashedPassword = await bcrypt.hash(password, 10);
  const currentUser = await User.create({ username, password: hashedPassword });
  ctx.body = {
    message: 'Add user',
    data: currentUser
  };
  return;
});

//http://localhost:3000/user/login
userRouter.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;

  const currentUser = await User.findOne({ where: { username } });
  if (!currentUser) {
    ctx.body = {
      code:500,
      message: 'User not found'
    };
    return;
  }

  const passwordMatch = await bcrypt.compare(password, currentUser.password);

  if (!passwordMatch) {
    ctx.body = {
      code:500,
      message: 'Incorrect password'
    };
    return;
  }

  const accessToken =
    "Bearer " +
    jwt.sign(
      {
        userId:currentUser.uid,
        username: currentUser.username,
      },
      "zshawk1982",
      {
        expiresIn: 3600 * 24 * 7,
      }
    );
  ctx.body = {
    code: 200,
    message: 'login success',
    data: { accessToken, currentUser }
  };
  return

});






//jwt--jsonwebtoken
//http://localhost:3000/user/login
// userRouter.post('/login', async (ctx, next) => {
//   const { username, password } = ctx.request.body;
//   console.log(111111,username)
//   const currentUser = await User.findOne({ where: { username } });
//   if (!currentUser) {
//     ctx.status = 401;
//     ctx.body = {
//       message: 'User not found'
//     };
//     return;
//   }
//   const passwordMatch = await bcrypt.compare(password, currentUser.password);
//   if (!passwordMatch) {
//     ctx.status = 401;
//     ctx.body = {
//       message: 'Incorrect password'
//     };
//     return;
//   }
//   const accessToken =
//     "Bearer " +
//     jwt.sign(
//       {
//         userId:currentUser.uid,
//         username: currentUser.username,
//       },
//       "zshawk1982",
//       {
//         expiresIn: 3600 * 24 * 7,
//       }
//     );
//   ctx.body = {
//     code: 200,
//     message: 'login success',
//     data: { accessToken, currentUser }
//   };
// });

module.exports = userRouter;